<!DOCTYPE html>












  


<html class="theme-next gemini use-motion" lang="zh-CN">
<head><meta name="generator" content="Hexo 3.8.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
























<link rel="stylesheet" href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2">

<link rel="stylesheet" href="/css/main.css?v=7.0.1">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=7.0.1">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=7.0.1">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=7.0.1">


  <link rel="mask-icon" href="/images/logo.svg?v=7.0.1" color="#222">







<script id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '7.0.1',
    sidebar: {"position":"left","display":"post","offset":12,"onmobile":false,"dimmer":false},
    back2top: true,
    back2top_sidebar: true,
    fancybox: false,
    fastclick: false,
    lazyload: false,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>


  




  <meta name="description" content="在多线程并发编程中，synchronized一直都是元老级别的角色，人们都通常称呼它为重量锁，但是在jdk1.6版本之后，jdk就对synchronized做了大量的优化，这时候我们就不能称呼它为重量锁了，有的时候它也是很轻的，那么接下来我们就调调，synchronized是怎么被优化的，它跟偏向锁、轻量锁、重量锁又有什么渊源。">
<meta name="keywords" content="java,多线程,synchronized">
<meta property="og:type" content="article">
<meta property="og:title" content="【java并发编程实战4】偏向锁-轻量锁-重量锁的那点秘密synchronize实现原理">
<meta property="og:url" content="http://www.yukonga.cn/2018/09/07/【java并发编程实战4】偏向锁-轻量锁-重量锁的那点秘密synchronize实现原理/index.html">
<meta property="og:site_name" content="yukong&#39;s blog">
<meta property="og:description" content="在多线程并发编程中，synchronized一直都是元老级别的角色，人们都通常称呼它为重量锁，但是在jdk1.6版本之后，jdk就对synchronized做了大量的优化，这时候我们就不能称呼它为重量锁了，有的时候它也是很轻的，那么接下来我们就调调，synchronized是怎么被优化的，它跟偏向锁、轻量锁、重量锁又有什么渊源。">
<meta property="og:locale" content="zh-CN">
<meta property="og:image" content="http://cdn.yukonga.cn/2019-05-07-062340.jpg">
<meta property="og:image" content="http://cdn.yukonga.cn/2019-05-07-062353.jpg">
<meta property="og:image" content="http://cdn.yukonga.cn/2019-05-07-055539.jpg">
<meta property="og:updated_time" content="2019-05-07T06:24:00.818Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="【java并发编程实战4】偏向锁-轻量锁-重量锁的那点秘密synchronize实现原理">
<meta name="twitter:description" content="在多线程并发编程中，synchronized一直都是元老级别的角色，人们都通常称呼它为重量锁，但是在jdk1.6版本之后，jdk就对synchronized做了大量的优化，这时候我们就不能称呼它为重量锁了，有的时候它也是很轻的，那么接下来我们就调调，synchronized是怎么被优化的，它跟偏向锁、轻量锁、重量锁又有什么渊源。">
<meta name="twitter:image" content="http://cdn.yukonga.cn/2019-05-07-062340.jpg">



  <link rel="alternate" href="/atom.xml" title="yukong's blog" type="application/atom+xml">




  <link rel="canonical" href="http://www.yukonga.cn/2018/09/07/【java并发编程实战4】偏向锁-轻量锁-重量锁的那点秘密synchronize实现原理/">



<script id="page.configurations">
  CONFIG.page = {
    sidebar: "",
  };
</script>

  <title>【java并发编程实战4】偏向锁-轻量锁-重量锁的那点秘密synchronize实现原理 | yukong's blog</title>
  






  <script>
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?45b7a3cfe46b3fa2c5d46f59f590664e";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>







  <noscript>
  <style>
  .use-motion .motion-element,
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-title { opacity: initial; }

  .use-motion .logo,
  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope="" itemtype="http://schema.org/WebPage" lang="zh-CN">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope="" itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">yukong's blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
    
      
        <p class="site-subtitle">learning program</p>
      
    
    
  </div>

  <div class="site-nav-toggle">
    <button aria-label="切换导航栏">
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>



<nav class="site-nav">
  
    <ul id="menu" class="menu">
      
        
        
        
          
          <li class="menu-item menu-item-home">

    
    
    
      
    

    

    <a href="/" rel="section"><i class="menu-item-icon fa fa-fw fa-home"></i> <br>首页</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-about">

    
    
    
      
    

    

    <a href="/about/" rel="section"><i class="menu-item-icon fa fa-fw fa-user"></i> <br>关于</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-tags">

    
    
    
      
    

    

    <a href="/tags/" rel="section"><i class="menu-item-icon fa fa-fw fa-tags"></i> <br>标签</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-categories">

    
    
    
      
    

    

    <a href="/categories/" rel="section"><i class="menu-item-icon fa fa-fw fa-th"></i> <br>分类</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-archives">

    
    
    
      
    

    

    <a href="/archives/" rel="section"><i class="menu-item-icon fa fa-fw fa-archive"></i> <br>归档</a>

  </li>

      
      
    </ul>
  

  

  
</nav>



  



</div>
    </header>

    


    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          
            

          
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  

  <article class="post post-type-normal" itemscope="" itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://www.yukonga.cn/2018/09/07/【java并发编程实战4】偏向锁-轻量锁-重量锁的那点秘密synchronize实现原理/">

    <span hidden itemprop="author" itemscope="" itemtype="http://schema.org/Person">
      <meta itemprop="name" content="yukong">
      <meta itemprop="description" content="你若对得起时间，时间便对得起你">
      <meta itemprop="image" content="/uploads/avatar.png">
    </span>

    <span hidden itemprop="publisher" itemscope="" itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="yukong's blog">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">【java并发编程实战4】偏向锁-轻量锁-重量锁的那点秘密synchronize实现原理

              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">

            
            
            

            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              

              
                
              

              <time title="创建时间：2018-09-07 08:26:12" itemprop="dateCreated datePublished" datetime="2018-09-07T08:26:12+08:00">2018-09-07</time>
            

            
              

              
                
                <span class="post-meta-divider">|</span>
                

                <span class="post-meta-item-icon">
                  <i class="fa fa-calendar-check-o"></i>
                </span>
                
                  <span class="post-meta-item-text">更新于</span>
                
                <time title="修改时间：2019-05-07 14:24:00" itemprop="dateModified" datetime="2019-05-07T14:24:00+08:00">2019-05-07</time>
              
            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope="" itemtype="http://schema.org/Thing"><a href="/categories/java并发编程实战/" itemprop="url" rel="index"><span itemprop="name">java并发编程实战</span></a></span>

                
                
              
            </span>
          

          
            
            
              
              <span class="post-comments-count">
                <span class="post-meta-divider">|</span>
                <span class="post-meta-item-icon">
                  <i class="fa fa-comment-o"></i>
                </span>
            
                <span class="post-meta-item-text">评论数：</span>
                <a href="/2018/09/07/【java并发编程实战4】偏向锁-轻量锁-重量锁的那点秘密synchronize实现原理/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count valine-comment-count" data-xid="/2018/09/07/【java并发编程实战4】偏向锁-轻量锁-重量锁的那点秘密synchronize实现原理/" itemprop="commentCount"></span>
                </a>
              </span>
            
          

          
          
            <span id="/2018/09/07/【java并发编程实战4】偏向锁-轻量锁-重量锁的那点秘密synchronize实现原理/" class="leancloud_visitors" data-flag-title="【java并发编程实战4】偏向锁-轻量锁-重量锁的那点秘密synchronize实现原理">
              <span class="post-meta-divider">|</span>
              <span class="post-meta-item-icon">
                <i class="fa fa-eye"></i>
              </span>
              
                <span class="post-meta-item-text">阅读次数：</span>
              
                <span class="leancloud-visitors-count"></span>
            </span>
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>在多线程并发编程中，synchronized一直都是元老级别的角色，人们都通常称呼它为<strong>重量锁</strong>，但是在jdk1.6版本之后，jdk就对synchronized做了大量的优化，这时候我们就不能称呼它为重量锁了，有的时候它也是很<strong>轻</strong>的，那么接下来我们就调调，synchronized是怎么被优化的，它跟偏向锁、轻量锁、重量锁又有什么渊源。</p>
<a id="more"></a>
<h1 id="synchronized"><a class="markdownIt-Anchor" href="#synchronized"></a> synchronized</h1>
<p>回顾一下synchronized是怎么使用的呢。</p>
<h2 id="1-同步普通方法"><a class="markdownIt-Anchor" href="#1-同步普通方法"></a> 1、同步普通方法</h2>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">synchronized</span> <span class="keyword">void</span>  <span class="title">sync1</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    <span class="comment">// do somethings</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>在该方法中，synchronized锁的是当前实例的对象</p>
<h2 id="2-同步静态方法"><a class="markdownIt-Anchor" href="#2-同步静态方法"></a> 2、同步静态方法</h2>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">synchronized</span> <span class="keyword">void</span> <span class="title">sync2</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    <span class="comment">// do somethings</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>由于该方法是一个静态方法，那么它锁的当前类的class对象。</p>
<h2 id="3-同步方法快"><a class="markdownIt-Anchor" href="#3-同步方法快"></a> 3、同步方法快</h2>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">sync3</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    <span class="keyword">synchronized</span>(<span class="keyword">this</span>) &#123;</span><br><span class="line">        <span class="comment">// do somethings</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">sync4</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    <span class="keyword">synchronized</span>(MyTest.css) &#123;</span><br><span class="line">        <span class="comment">// do somethings</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>那么同步方法快是需要根据方法中具体同步的对象来实现的。</p>
<p>在上面代码中其实<code>sync3()</code>跟同步普通方法一样，锁的是当前实例对象；那么<code>sync4</code>方法就与同步静态方法一样，锁的是当前类的class对象。</p>
<p>从上面代码可以看出来的，我们通过使用<code>synchronized</code>关键字可以很简单的解决并发问题，但是其实是jvm底层通过使用一种叫内置锁的手段，简化了开发人员实现并发的复杂度，在jdk1.6以前 synchronized是基于重量锁实现的，即每次遇到同步代码都要获取锁，然后释放锁，在jdk1.6之后对其优化，根据不同场景使用不同的策略，这也就是 偏向锁、轻量锁、重量锁的来由。在介绍他们之前我先介绍一下另一个锁-自旋锁。听到这么多锁，是不是头晕，当初我学习的时候也是这样的。但是当你慢慢学习深入，你就会很容易的理解每个锁的作用。</p>
<h1 id="自旋锁"><a class="markdownIt-Anchor" href="#自旋锁"></a> 自旋锁</h1>
<p>自旋锁顾名思义，就是自己旋转转圈等待，那么它有什么作用呢？</p>
<ul>
<li>当前线程尝试去竞争锁</li>
<li>竞争失败，准备阻塞自己</li>
<li>但是并没有阻塞自己，而是采用自旋锁，进入自旋状态</li>
<li>进入自旋状态，并且重新不断竞争锁</li>
<li>如果在自旋期间成功获取锁，那么结束自旋状态，否则进入阻塞状态</li>
</ul>
<blockquote>
<p>如果在自旋期间成功获取锁，那么就减少一次线程的切换。</p>
</blockquote>
<p>根据上面解释我们可以很容易的明白自旋锁的意义，因为cpu从内核态切换至用户态，线程的阻塞与恢复会浪费资源的，但是通过自旋而不是去阻塞当前线程，那么就会节省这个一个cpu状态切换。</p>
<p>所以自旋锁适合在** 持有锁的时间长，且竞争不激烈**的场景下使用。</p>
<blockquote>
<p>使用-XX:-UseSpinning参数关闭自旋锁优化；-XX:PreBlockSpin参数修改默认的自旋次数</p>
</blockquote>
<h1 id="偏向锁"><a class="markdownIt-Anchor" href="#偏向锁"></a> 偏向锁</h1>
<p>在实际场景中，如果一个同步方法，没有多线程竞争，并且总是由同一个线程多次获取锁，如果每次还有阻塞线程，唤醒cpu从用户态转核心态，那么对于cpu是一种资源的浪费，为了解决这类问题，旧引入了偏向锁的概念。</p>
<p>“偏向”的意思是，<em>偏向锁假定将来只有第一个申请锁的线程会使用锁</em>（不会有任何线程再来申请锁），因此，<em>只需要在Mark Word中CAS记录owner（本质上也是更新，但初始值为空），如果记录成功，则偏向锁获取成功</em>，记录锁状态为偏向锁，<em>以后当前线程等于owner就可以零成本的直接获得锁；否则，说明有其他线程竞争，膨胀为轻量级锁</em>。</p>
<p>具体的步骤如下</p>
<ul>
<li>
<p>访问同步代码块</p>
</li>
<li>
<p>检查对象头是否owner是否存储当前现成的id</p>
</li>
<li>
<p>如果没有，进行CAS尝试替换mark word中的owner  如果有执行同步代码（代表获取锁成功）</p>
</li>
<li>
<p>修改成功 （代表无竞争）owner修改为当前线程id,执行同步代码 修改失败(代表有竞争) 进入撤销偏向锁，暂停线程并将owner置空，进入轻量锁。</p>
</li>
</ul>
<p><img src="http://cdn.yukonga.cn/2019-05-07-062340.jpg" alt=""></p>
<p>偏向锁无法使用自旋锁优化，因为一旦有其他线程申请锁，就破坏了偏向锁的假定。</p>
<blockquote>
<p>如果你确定应用程序中所有的锁通常是在竞争状态，你可以通过JVM参数关闭偏向锁</p>
<p>UseBiasedLocking = false，那么程序会默认进入轻量锁状态。</p>
</blockquote>
<h1 id="轻量锁"><a class="markdownIt-Anchor" href="#轻量锁"></a> 轻量锁</h1>
<p>如果说偏向锁是为了解决同步代码在单线程下访问性能问题，那么轻量锁是为了解决<strong>减少无实际竞争情况下，使用重量级锁产生的性能消耗</strong></p>
<p>轻量锁，顾名思义，轻量是相对于重量的问题，使用轻量锁时，不需要申请互斥量(mutex)</p>
<p>,而是将mark word中的信息复制到当前线程的栈中，然后通过cas尝试修改mark word并替换成轻量锁，如果替换成功则执行同步代码。如果此时有线程2来竞争，并且他也尝试cas修改mark word但是失败了，那么线程2会进入自旋状态，如果在自旋状态也没有修改成功，那么轻量锁将膨胀成状态，mark word会被修改成重量锁标记(10) ,线程进入阻塞状态。</p>
<p>当然，由于轻量级锁天然瞄准不存在锁竞争的场景，如果存在锁竞争但不激烈，仍然可以用自旋锁优化，<em>自旋失败后再膨胀为重量级锁</em>。</p>
<h1 id="重量锁"><a class="markdownIt-Anchor" href="#重量锁"></a> 重量锁</h1>
<p>在jvm规范中，synchronized是基于监视器锁(monitor)来实现的，它会在同步代码之前添加一个<code>monitorenter</code>指令，获取到该对象的monitor，同时它会在同步代码结束处和异常处添加一个<code>monitorexit</code>指令去释放该对象的monitor,需要注意的是每一个对象都有一个monitor与之配对，当一个monitor被获取之后 也就是被<code>monitorenter</code>，它会处于一个锁定状态，其他尝试获取该对象的monitor的线程会获取失败，只有当获取该对象的monitor的线程执行了<code>monitorexit</code>指令后，其他线程才有可能获取该对象的monitor成功。</p>
<p>所以从上面描述可以得出，监视器锁就是<code>monitor</code>它是互斥的(mutex)。由于它是互斥的，那么它的操作成本就非常的高，包括系统调用引起的内核态与用户态切换、线程阻塞造成的线程切换等。因此，后来称这种锁为“重量级锁”。</p>
<h1 id="小结"><a class="markdownIt-Anchor" href="#小结"></a> 小结</h1>
<p>偏向锁、轻量级锁、重量级锁适用于不同的并发场景：</p>
<ul>
<li>偏向锁：无实际竞争，且将来只有第一个申请锁的线程会使用锁。</li>
<li>轻量级锁：无实际竞争，多个线程交替使用锁；允许短时间的锁竞争。</li>
<li>重量级锁：有实际竞争，且锁竞争时间长。</li>
</ul>
<p>另外，如果锁竞争时间短，可以使用自旋锁进一步优化轻量级锁、重量级锁的性能，减少线程切换。</p>
<p>如果锁竞争程度逐渐提高（缓慢），那么从偏向锁逐步膨胀到重量锁，能够提高系统的整体性能。<br>
同时需要注意<strong>锁可以升级，但是不能降级</strong>。</p>
<p>另外通过这次学习，大家应该也知道自从jdk1.6以后 <code>synchronized</code>已经被优化了，性能不会比<code>Lock</code>差</p>
<p>所以jdk.16版本及其以后版本的同学可以放心大胆的使用了。</p>
<p>最后附一张从偏向锁膨胀至重量锁的完全的流程图</p>
<p><img src="http://cdn.yukonga.cn/2019-05-07-062353.jpg" alt=""></p>
<p>欢迎大家关注一下我的个人公众号。一起交流一起学习，有问必答。</p>
<p><img src="http://cdn.yukonga.cn/2019-05-07-055539.jpg" alt=""></p>

      
    </div>

    

    
    
    

    

    
      
    
    
      <div>
        <div id="reward-container">
  <div>喜欢就请博主喝个☕️吧</div>
  <button id="reward-button" disable="enable" onclick="var qr = document.getElementById(&quot;qr&quot;); qr.style.display = (qr.style.display === 'none') ? 'block' : 'none';">
    打赏
  </button>
  <div id="qr" style="display: none;">

    
      
      
        
      
      <div style="display: inline-block">
        <img src="/images/wechatpay.jpg" alt="yukong 微信支付">
        <p>微信支付</p>
      </div>
    
      
      
        
      
      <div style="display: inline-block">
        <img src="/images/alipay.jpg" alt="yukong 支付宝">
        <p>支付宝</p>
      </div>
    

  </div>
</div>

      </div>
    

    
      <div>
        




  



<ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者： </strong>yukong</li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    
    <a href="http://www.yukonga.cn/2018/09/07/【java并发编程实战4】偏向锁-轻量锁-重量锁的那点秘密synchronize实现原理/" title="【java并发编程实战4】偏向锁-轻量锁-重量锁的那点秘密synchronize实现原理">http://www.yukonga.cn/2018/09/07/【java并发编程实战4】偏向锁-轻量锁-重量锁的那点秘密synchronize实现原理/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc/4.0/" rel="noopener" target="_blank"><i class="fa fa-fw fa-creative-commons"></i>BY-NC</a> 许可协议。转载请注明出处！</li>
</ul>

      </div>
    
    

      <div>
        <div>
    
        <div style="text-align:center;color: #ccc;font-size:14px;">-------------本文结束<i class="fa fa-paw"></i>感谢您的阅读-------------</div>
    
</div>

      </div>
    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/java/" rel="tag"><i class="fa fa-tag"></i> java</a>
          
            <a href="/tags/多线程/" rel="tag"><i class="fa fa-tag"></i> 多线程</a>
          
            <a href="/tags/synchronized/" rel="tag"><i class="fa fa-tag"></i> synchronized</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2018/09/04/【SpringBoot2-0系列11】SpringBoot之-Elasticsearch完成CURD/" rel="next" title="【SpringBoot2.0系列11】SpringBoot之@Elasticsearch完成CURD">
                <i class="fa fa-chevron-left"></i> 【SpringBoot2.0系列11】SpringBoot之@Elasticsearch完成CURD
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2018/09/07/【java并发编程实战5】线程与线程通信/" rel="prev" title="【java并发编程实战5】线程与线程通信">
                【java并发编程实战5】线程与线程通信 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>


  </div>


          </div>
          

  
    <div class="comments" id="comments">
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope="" itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image" src="/uploads/avatar.png" alt="yukong">
            
              <p class="site-author-name" itemprop="name">yukong</p>
              <div class="site-description motion-element" itemprop="description">你若对得起时间，时间便对得起你</div>
          </div>

          
            <nav class="site-state motion-element">
              
                <div class="site-state-item site-state-posts">
                
                  <a href="/archives/">
                
                    <span class="site-state-item-count">26</span>
                    <span class="site-state-item-name">日志</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-categories">
                  
                    
                      <a href="/categories/">
                    
                  
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">6</span>
                    <span class="site-state-item-name">分类</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-tags">
                  
                    
                      <a href="/tags/">
                    
                  
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">36</span>
                    <span class="site-state-item-name">标签</span>
                  </a>
                </div>
              
            </nav>
          

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          

          
            <div class="links-of-author motion-element">
              
                <span class="links-of-author-item">
                  
                  
                    
                  
                  
                    
                  
                  <a href="https://github.com/YuKongEr" title="GitHub &rarr; https://github.com/YuKongEr" rel="noopener" target="_blank"><i class="fa fa-fw fa-github"></i>GitHub</a>
                </span>
              
                <span class="links-of-author-item">
                  
                  
                    
                  
                  
                    
                  
                  <a href="mailto:yukongcode@gmail.com" title="E-Mail &rarr; mailto:yukongcode@gmail.com" rel="noopener" target="_blank"><i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                </span>
              
                <span class="links-of-author-item">
                  
                  
                    
                  
                  
                    
                  
                  <a href="https://www.jianshu.com/u/bc2e35b66293" title="简书 &rarr; https://www.jianshu.com/u/bc2e35b66293" rel="noopener" target="_blank"><i class="fa fa-fw fa-skype"></i>简书</a>
                </span>
              
                <span class="links-of-author-item">
                  
                  
                    
                  
                  
                    
                  
                  <a href="https://blog.csdn.net/xp541130126" title="csdn &rarr; https://blog.csdn.net/xp541130126" rel="noopener" target="_blank"><i class="fa fa-fw fa-vk"></i>csdn</a>
                </span>
              
            </div>
          

          

          
          

          
            
          
          

        </div>
      </div>

      
      <!--noindex-->
        <div class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
            
            
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#synchronized"><span class="nav-number">1.</span> <span class="nav-text"> synchronized</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#1-同步普通方法"><span class="nav-number">1.1.</span> <span class="nav-text"> 1、同步普通方法</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2-同步静态方法"><span class="nav-number">1.2.</span> <span class="nav-text"> 2、同步静态方法</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#3-同步方法快"><span class="nav-number">1.3.</span> <span class="nav-text"> 3、同步方法快</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#自旋锁"><span class="nav-number">2.</span> <span class="nav-text"> 自旋锁</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#偏向锁"><span class="nav-number">3.</span> <span class="nav-text"> 偏向锁</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#轻量锁"><span class="nav-number">4.</span> <span class="nav-text"> 轻量锁</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#重量锁"><span class="nav-number">5.</span> <span class="nav-text"> 重量锁</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#小结"><span class="nav-number">6.</span> <span class="nav-text"> 小结</span></a></li></ol></div>
            

          </div>
        </div>
      <!--/noindex-->
      

      
        <div class="back-to-top">
          <i class="fa fa-arrow-up"></i>
          
            <span id="scrollpercent"><span>0</span>%</span>
          
        </div>
      

    </div>
  </aside>
  


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2020</span>
  <span class="with-love" id="animate">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">yukong</span>

  

  
</div>
<div class="BbeiAn-info">
浙ICP备 -
<a target="_blank" href="http://www.miitbeian.gov.cn">19015067号</a>

</div>









        
<div class="busuanzi-count">
  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="post-meta-item-icon">
      <i class="fa fa-user"></i>
      您是访问本站的第&nbsp
    </span>
    <span class="site-uv" title="总访客量">
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
      &nbsp 位朋友
    </span>
  

  
    <span class="post-meta-divider">|</span>
  

  
    <span class="post-meta-item-icon">
      <i class="fa fa-eye"></i>
      本站总共访问&nbsp
    </span>
    <span class="site-pv" title="总访问量">
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
      次
    </span>
  
</div>









        
      </div>
    </footer>

    

    

    

    
  </div>

  

<script>
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>


























  
  <script src="/lib/jquery/index.js?v=2.1.3"></script>

  
  <script src="/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>


  


  <script src="/js/src/utils.js?v=7.0.1"></script>

  <script src="/js/src/motion.js?v=7.0.1"></script>



  
  


  <script src="/js/src/affix.js?v=7.0.1"></script>

  <script src="/js/src/schemes/pisces.js?v=7.0.1"></script>




  
  <script src="/js/src/scrollspy.js?v=7.0.1"></script>
<script src="/js/src/post-details.js?v=7.0.1"></script>



  


  <script src="/js/src/next-boot.js?v=7.0.1"></script>


  

  

  

  
  

<script src="//cdn1.lncld.net/static/js/3.11.1/av-min.js"></script>



<script src="//unpkg.com/valine/dist/Valine.min.js"></script>

<script>
  var GUEST = ['nick', 'mail', 'link'];
  var guest = 'nick,mail,link';
  guest = guest.split(',').filter(function(item) {
    return GUEST.indexOf(item) > -1;
  });
  new Valine({
    el: '#comments',
    verify: false,
    notify: false,
    appId: 'UXuVTqzKQgCJRWTkO8K60EXL-gzGzoHsz',
    appKey: 'n3ohmj1CGAM1GUfp6SqF4LXh',
    placeholder: 'Just go go',
    avatar: 'mm',
    meta: guest,
    pageSize: '10' || 10,
    visitor: false,
    lang: 'zh-cn' || 'zh-cn'
  });
</script>




  


  




  
  
  <script>
    
    function addCount(Counter) {
      var $visitors = $('.leancloud_visitors');
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();

      Counter('get', '/classes/Counter', { where: JSON.stringify({ url }) })
        .done(function({ results }) {
          if (results.length > 0) {
            var counter = results[0];
            
            Counter('put', '/classes/Counter/' + counter.objectId, JSON.stringify({ time: { '__op': 'Increment', 'amount': 1 } }))
            
              .done(function() {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.time + 1);
              })
            
              .fail(function ({ responseJSON }) {
                console.log('Failed to save Visitor num, with error message: ' + responseJSON.error);
              })
          } else {
            
              Counter('post', '/classes/Counter', JSON.stringify({ title: title, url: url, time: 1 }))
                .done(function() {
                  var $element = $(document.getElementById(url));
                  $element.find('.leancloud-visitors-count').text(1);
                })
                .fail(function() {
                  console.log('Failed to create');
                });
            
          }
        })
        .fail(function ({ responseJSON }) {
          console.log('LeanCloud Counter Error: ' + responseJSON.code + ' ' + responseJSON.error);
        });
    }
    

    $(function() {
      $.get('https://app-router.leancloud.cn/2/route?appId=' + 'UXuVTqzKQgCJRWTkO8K60EXL-gzGzoHsz')
        .done(function({ api_server }) {
          var Counter = function(method, url, data) {
            return $.ajax({
              method: method,
              url: 'https://' + api_server + '/1.1' + url,
              headers: {
                'X-LC-Id': 'UXuVTqzKQgCJRWTkO8K60EXL-gzGzoHsz',
                'X-LC-Key': 'n3ohmj1CGAM1GUfp6SqF4LXh',
                'Content-Type': 'application/json',
              },
              data: data
            });
          };
          
            addCount(Counter);
          
        });
    });
  </script>



  

  

  

  

  

  

  

  

  

  

  
<script>
  $('.highlight').each(function(i, e) {
    var $wrap = $('<div>').addClass('highlight-wrap');
    $(e).after($wrap);
    $wrap.append($('<button>').addClass('copy-btn').append('复制').on('click', function(e) {
      var code = $(this).parent().find('.code').find('.line').map(function(i, e) {
        return $(e).text();
      }).toArray().join('\n');
      var ta = document.createElement('textarea');
      var yPosition = window.pageYOffset || document.documentElement.scrollTop;
      ta.style.top = yPosition + 'px'; // Prevent page scroll
      ta.style.position = 'absolute';
      ta.style.opacity = '0';
      ta.readOnly = true;
      ta.value = code;
      document.body.appendChild(ta);
      ta.select();
      ta.setSelectionRange(0, code.length);
      ta.readOnly = false;
      var result = document.execCommand('copy');
      
        if (result) $(this).text('复制成功');
        else $(this).text('复制失败');
      
      ta.blur(); // For iOS
      $(this).blur();
    })).on('mouseleave', function(e) {
      var $b = $(this).find('.copy-btn');
      setTimeout(function() {
        $b.text('复制');
      }, 300);
    }).append(e);
  })
</script>


  

  

</body>
</html>
